﻿using System.Net.Mail;
using Foothill.Common;
using System;
using Foothill.Service.Configuration;

namespace Foothill.Service.Email
{
    public class EmailService : IEmailService
    {
        private readonly IEmailSender _emailSender;
        private readonly IHostSettingManager _hostSettingManager;

        public EmailService(IEmailSender emailSender, IHostSettingManager hostSettingManager)
        {
            _emailSender = emailSender;
            _hostSettingManager = hostSettingManager;
        }
        
        public bool SendNewPostNotification(int newPostId, string editKey, string toEmailAddress)
        {
            string emailContent = "感谢在温哥华二手车网发帖\n";
            emailContent += string.Format("要撤销广告，请点击: {0}", BuildEditPostLink(newPostId, editKey));

            using (MailMessage mailMessage = new MailMessage())
            {
                mailMessage.Subject = "温哥华二手车网";
                mailMessage.Body = emailContent;
                mailMessage.IsBodyHtml = true;

                mailMessage.To.Add(new MailAddress(toEmailAddress));

                try
                {
                    _emailSender.SendEmail(mailMessage);
                }
                catch (Exception)
                {
                    return false;
                }
            }

            return true;
        }

        public string BuildEditPostLink(int postId, string editKey)
        {
            Uri uri = new Uri(_hostSettingManager.GetSiteBaseUri(), string.Format("/EditPost/EditPost.aspx?{0}={1}&{2}={3}", GlobalQueryString.EditPostIdQsName, postId, GlobalQueryString.EditPostEditKeyQsName, editKey));
            return uri.ToString();
        }
    }
}
